﻿#include <algorithm>
#include <boost/algorithm/string.hpp>
#include <boost/asio.hpp>
#include <iostream>
#include <semaphore>
#include <shared_mutex>
#include <sstream>
#include <string>
#include <thread>
#include <vector>

#include "DataSaver.h"
#include "SerialLogger.h"

using namespace boost;

std::vector<std::string>* get_all_serial_port_devices()
{
    std::vector<std::string>* ret = new std::vector<std::string>;
    for (int i = 0; i < 20; i++)
    {
        asio::io_service  io_service;
        asio::serial_port m_serial_port(io_service);
        try
        {
            std::string dev_name = "COM" + std::to_string(i);
            m_serial_port.open(dev_name);
            ret->push_back(dev_name);
        }
        catch (boost::system::system_error err)
        {
            // 该串口不可用
        }
        if (m_serial_port.is_open())
        {
            m_serial_port.close();
        }
    }
    return ret;
}

int main()
{
    std::cout << "当前可用设备：" << std::endl;
    auto dev_list = get_all_serial_port_devices();
    for (auto dev_name : *dev_list)
    {
        std::cout << dev_name << std::endl;
    }
    delete dev_list;

    std::cout << "请输入要读取的设备号，使用空格分割：" << std::endl;
    char str_dev_index_list[128];
    std::cin.getline(str_dev_index_list, sizeof(str_dev_index_list));

    std::vector<std::string> arr_str_dev_index_list;
    split(arr_str_dev_index_list, str_dev_index_list, is_any_of(" "), token_compress_on);
    std::vector<std::thread> thread_list;

    DataSaver saver;

    // 每个串口设备启动一个线程
    std::for_each(arr_str_dev_index_list.begin(), arr_str_dev_index_list.end(), [&thread_list, &saver](std::string& serial_index) {
        thread_list.push_back(std::thread([&serial_index, &saver]() {
            SerialLogger s = "COM" + serial_index;
            s.open(&saver);
        }));
    });

    std::cout << "按任意键结束";
    std::cin.get();

    // 关闭输出文件流
    DataSaver::out_file.close();
}
